import 'package:earclean/app/request/request_main.dart';
import 'package:earclean/app/routes/app_pages.dart';
import 'package:earclean/app/util/common_utils.dart';
import 'package:earclean/app/util/pay_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:fluwx/fluwx.dart';
import 'package:fluwx/fluwx.dart' as fluwx;

//  with WidgetsBindingObserver
class PayController extends GetxController {
  //TODO: Implement PayController

  final paytype = 2.obs;
  final price = 0.obs;

  final showWx = false.obs;
  final showZfb = false.obs;

  String order_sn = '';
  bool ispay = false;

  Map info = {};
  @override
  void onInit() {
    info = Get.arguments;
    price.value = (info['price'] ?? 0) * (info['num'] ?? 0);
    // WidgetsBinding.instance.addObserver(this);
    List pconfs = box.read('pconfs');
    pconfs.forEach((element) {
      if (element['type'] == 2) {
        showWx.value = true;
        if (element['def'] == 1) {
          paytype.value = 2;
        }
      } else if (element['type'] == 1) {
        showZfb.value = true;
        if (element['def'] == 1) {
          paytype.value = 1;
        }
      }
    });
    // //支付回调监听
    fluwx.weChatResponseEventHandler.listen((BaseWeChatResponse event) {
      if (event is fluwx.WeChatPaymentResponse) {
        if (event.isSuccessful) {
          EasyLoading.show(status: '加载中...');
          RequestMain.getUrl({'order_sn': order_sn},
                  turl: 'https://fjbamz.jiliol.net/sign/?a=paystate')
              .then((value) {
            EasyLoading.dismiss();
            if (value.isNotEmpty && value['code'].toString() == "200") {
              order_sn = '';
              Get.offNamed(Routes.PAYEND, arguments: {
                'price': price.value,
                'paytype': paytype.value,
              });
            } else {
              EasyLoading.showToast('支付未成功，请重新支付');
            }
          });
          // EasyLoading.showToast('支付回调监听');

        } else {
          EasyLoading.showToast('支付未成功，请重新支付');
        }
      }
    });

    super.onInit();
  }

  // @override
  // void didChangeAppLifecycleState(AppLifecycleState state) {
  //   switch (state) {
  //     case AppLifecycleState.resumed:
  //       if (ispay == true) {
  //         ispay = false;
  //         EasyLoading.show(status: '加载中...');
  //         RequestMain.getUrl({'order_sn': order_sn},
  //                 turl: 'https://fjbamz.jiliol.net/sign/?a=paystate')
  //             .then((value) {
  //           EasyLoading.dismiss();
  //           if (value.isNotEmpty && value['code'].toString() == "200") {
  //             order_sn = '';
  //             Get.offNamed(Routes.PAYEND, arguments: {
  //               'price': price.value,
  //               'paytype': paytype.value,
  //             });
  //           } else {
  //             EasyLoading.showToast('支付未成功，请重新支付');
  //           }
  //         });
  //       }
  //       break;
  //     default:
  //   }
  // }

  pay() async {
    // String project_price = info['project_price'].replaceAll("元", "");

    final result = await RequestMain.postUrl({
      'user_id': 0, //技师用户UID
      'cate_id': 11, //品类ID（可以为空，但不能没有）
      'price': price, //价格
      'type': paytype.value, //
      'src': '1'
    }, turl: 'https://fjbamz.jiliol.net/sign/?a=need');
    print(result);
    // {code: 200, msg: 操作成功, data: {sign: {appid: wx8a7e432a49974df9, partnerid: 1627670432, prepayid: wx23173004888070f266cba27d7e556f0001, package: Sign=WXPay, noncestr: b025f7dc5927fed0ef419ec045efda46, timestamp: 1713864604, package_: Sign=WXPay, link: https://fjbamz.jiliol.net/apple-app-site-association, signPay: 7D5CC341F324A3020328D445B30E2BAA, orderId: CPUARF9431PD4I8CV1MP03RPPF}, order_sn: CPUARF9431PD4I8CV1MP03RPPF, type: 2, id: 14150460400008}}
    if (result.isNotEmpty && result['code'].toString() == "200") {
      order_sn = result["data"]['order_sn'];
      ispay = true;
      if (paytype.value == 1) {
        //支付宝支付
        PayUtils.alipay(result["data"]['sign']).then((value) {
          if (value) {
            EasyLoading.show(status: '加载中...');
            RequestMain.getUrl({'order_sn': order_sn},
                    turl: 'https://fjbamz.jiliol.net/sign/?a=paystate')
                .then((value) {
              EasyLoading.dismiss();
              if (value.isNotEmpty && value['code'].toString() == "200") {
                order_sn = '';
                Get.offNamed(Routes.PAYEND, arguments: {
                  'price': price.value,
                  'paytype': paytype.value,
                });
              } else {
                EasyLoading.showToast('支付未成功，请重新支付');
              }
            });
          } else {
            EasyLoading.showToast('支付未成功，请重新支付');
          }
        });
      } else {
        // 微信支
        bool a = await PayUtils.wxpay(
            Map<String, dynamic>.from(result["data"]['sign']));
        if (a) {
          // Future.delayed(const Duration(milliseconds: 500), () {
          //   // Get.offNamed(Routes.PAYEND, arguments: {'info': info});
          //   Get.offNamed(Routes.PAYEND, arguments: {
          //     'price': price.value,
          //     'paytype': paytype.value,
          //   });
          // });
        }
      }
    }
    // 调用支付
    // 支付成功
    //
  }

  // pay() {
  //   // 保存订单
  //   // 时间
  //   String dateTime = DateTime.now().toString().split('.')[0];
  //   //
  //   // 获取数据
  //   List orderList = box.read('orderList') ?? [];

  //   orderList.add({
  //     ...info,
  //     'dateTime': dateTime,
  //   });
  //   // 存储数据
  //   // box.write("orderList", orderList);

  //   // Get.offNamed(Routes.PAYEND, arguments: {
  //   //   'price':price.value,
  //   //   'paytype':paytype.value,
  //   // });
  // }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    print('查询支付专题');
    // WidgetsBinding.instance.removeObserver(this);
  }
}
